package com.ds.robot.assistant.service.yunxiao;

import com.aliyun.sdk.service.devops20210625.models.ListOrganizationMembersRequest;
import com.aliyun.sdk.service.devops20210625.models.ListOrganizationMembersResponse;
import com.aliyun.sdk.service.devops20210625.models.ListOrganizationMembersResponseBody;
import com.google.common.collect.Lists;
import com.ds.robot.assistant.entity.EmpInfoEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.PreDestroy;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 作用：
 *
 * @author WeiShaoying
 * 
 */

@Component
@Slf4j
@SuppressWarnings("SpellCheckingInspection")
public class YunXiaoMemberClient extends YunXiaoBase {

    @PreDestroy
    private void destroy() {
        log.info("云效成员Client准备关闭");
        asyncClient.close();
        log.info("云效成员Client关闭成功");
    }

    /**
     * 查询组织人员列表
     *
     * @return
     */
    public List<EmpInfoEntity> queryOrgEmpList() {
        List<EmpInfoEntity> list = Lists.newArrayList();
        long start = System.currentTimeMillis();

        // Parameter settings for API request
        ListOrganizationMembersRequest listOrganizationMembersRequest = ListOrganizationMembersRequest.builder()
                .organizationId(ORGANIZATION_ID)
                .maxResults(200L)
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<ListOrganizationMembersResponse> response = asyncClient.listOrganizationMembers(listOrganizationMembersRequest);
        // Synchronously get the return value of the API request
        ListOrganizationMembersResponse resp = response.join();
        if (resp != null && resp.getStatusCode().equals(200)) {
            ListOrganizationMembersResponseBody body = resp.getBody();
            if (Objects.isNull(body)) {
                return Collections.emptyList();
            }
            List<ListOrganizationMembersResponseBody.Members> memberList = body.getMembers();
            if (CollectionUtils.isEmpty(memberList)) {
                log.warn("查询组织人员为空");
                return Collections.emptyList();
            }
            log.info("查询组织人员数量={}", body.getTotalCount());
            list = memberList.stream().map(member -> {
                EmpInfoEntity entity = new EmpInfoEntity();
                entity.setAccountId(member.getAccountId());
                String memberName = member.getOrganizationMemberName();
                if (StringUtils.hasText(memberName) && memberName.contains("（")) {
                    entity.setName(memberName.substring(0, memberName.indexOf("（")));
                } else {
                    entity.setName(memberName);
                }
                entity.setRoleId(member.getOrganizationRoleId());
                entity.setRoleName(member.getOrganizationRoleName());
                entity.setState(member.getState());
                return entity;
            }).collect(Collectors.toList());
        }

        // System.out.println(new Gson().toJson(resp));
        // Asynchronous processing of return values
        /*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handling exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*/

        // 关闭后再次调用会报错
        // asyncClient.close();
        long end = System.currentTimeMillis();
        log.info("查询组织人员耗时：{}毫秒 ", (end - start));

        return list;
    }

}
